package com.css.dzj.dzjap.modules.jgxwother.service.impl;

import com.css.aq.server.service.BaseService;
import com.css.dzj.dzjap.common.util.Constant;
import com.css.dzj.dzjap.common.util.R;
import com.css.dzj.dzjap.common.util.ServiceUtil;
import com.css.dzj.dzjap.common.util.SnowflakeId;
import com.css.dzj.dzjap.modules.apunit.entity.ApUnitEntity;
import com.css.dzj.dzjap.modules.jgxwother.dao.OtherDao;
import com.css.dzj.dzjap.modules.jgxwother.entity.JgJgxwOtherActionEntity;
import com.css.dzj.dzjap.modules.jgxwother.entity.QJgJgxwOtherActionEntity;
import com.css.dzj.dzjap.modules.jgxwother.service.OtherService;
import com.css.dzj.dzjap.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.ComparableExpressionBase;
import com.querydsl.core.types.dsl.NumberExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OtherServiceImpl implements OtherService {

    @Autowired
    private OtherDao otherDao;

    //注入JPAQueryFactory工厂
    @Autowired
    JPAQueryFactory jpaQueryFactory;
    @Autowired
    ServiceUtil serviceUtil;
    /**
     *
     * 查询其他行为信息表
     * @return
     */
    @Override
    public JgJgxwOtherActionEntity getOther(String actionId) {
        if(StringUtils.isEmpty(actionId)){

            throw new RuntimeException("参数为空");
        }
        QJgJgxwOtherActionEntity qOther = QJgJgxwOtherActionEntity.jgJgxwOtherActionEntity;
        return jpaQueryFactory
                .selectFrom(qOther)
                .where( qOther.actionId.eq(actionId),
                        qOther.delFlag.eq(Constant.NO_DELETE)
                )
                .fetchOne();
    }

    /**
     *
     * 添加其他行为信息表
     * @return
     */
    @Override
    @Transactional
    public String addOther(JgJgxwOtherActionEntity other) {

        other.setDelFlag(Constant.NO_DELETE);
        other.setActionId(SnowflakeId.getId());
        other.setCreateTime(new Date());
        try {
            otherDao.save(other);
            return other.getActionId();

        }catch (Exception e){
            return "0";
        }
    }

    /**
     *修改其他行为信息表
     *
     */
    @Override
    @Transactional
    public void update(JgJgxwOtherActionEntity other) {


    }

    /**
     *
     * 删除其他行为信息表
     */
    @Override
    @Transactional
    public Boolean deleteOther(String actionId) {
        QJgJgxwOtherActionEntity qOther = QJgJgxwOtherActionEntity.jgJgxwOtherActionEntity;
        if(StringUtils.isEmpty(actionId)){
            return  false;
        }
        try{
            jpaQueryFactory
                    .update(qOther)
                    .set(qOther.delFlag,Constant.DELETE)
                    .where(
                            qOther.delFlag.eq(Constant.NO_DELETE),
                            qOther.actionId.eq(actionId)
                    )
                    .execute();
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 分页查询
     * @param pageable
     * @return
     */
    @Override
    public QueryResults<JgJgxwOtherActionEntity> getAllOther(Pageable pageable) {

        QJgJgxwOtherActionEntity qOther = QJgJgxwOtherActionEntity.jgJgxwOtherActionEntity;
        Predicate predicate = qOther.isNotNull().or(qOther.isNull());
        predicate = ExpressionUtils.and(predicate, qOther.delFlag.eq(Constant.NO_DELETE)) ;

        return  jpaQueryFactory
                .selectFrom(qOther)
                .where(
                        predicate
                )
                .orderBy(qOther.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }

    /**
     * 多条件分页查询
     */
    @Override
    public QueryResults<JgJgxwOtherActionEntity> getAllConOther(Pageable pageable, String superviseItemCode, String recordUniqueIdentity, String actionName, String actionCode, String checkBehaviorNumber, String superviseObject) {

        QJgJgxwOtherActionEntity qOther = QJgJgxwOtherActionEntity.jgJgxwOtherActionEntity;
        Predicate predicate = qOther.isNotNull().or(qOther.isNull());
        predicate = ("".equals(superviseItemCode) || superviseItemCode == null) ? predicate : ExpressionUtils.and(predicate, qOther.superviseItemCode.like("%"+superviseItemCode+"%"));
        predicate = ("".equals(recordUniqueIdentity) || recordUniqueIdentity == null) ? predicate : ExpressionUtils.and(predicate, qOther.recordUniqueIdentity.like("%"+recordUniqueIdentity+"%"));
        predicate = ("".equals(actionName) || actionName == null) ? predicate : ExpressionUtils.and(predicate, qOther.actionName.like("%"+actionName+"%"));
        predicate = ("".equals(actionCode) || actionCode == null) ? predicate : ExpressionUtils.and(predicate, qOther.actionCode.like("%"+actionCode+"%"));
        predicate = ("".equals(checkBehaviorNumber) || checkBehaviorNumber == null) ? predicate : ExpressionUtils.and(predicate, qOther.checkBehaviorNumber.like("%"+checkBehaviorNumber+"%"));
        predicate = ("".equals(superviseObject) || superviseObject == null) ? predicate : ExpressionUtils.and(predicate, qOther.superviseObject.like("%"+superviseObject+"%"));
        predicate = ExpressionUtils.and(predicate, qOther.delFlag.eq(Constant.NO_DELETE)) ;

        return  jpaQueryFactory
                .selectFrom(qOther)
                .where(
                        predicate
                )
                .orderBy(qOther.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }

    @Override
    public HashMap getCount() {
        QJgJgxwOtherActionEntity q=QJgJgxwOtherActionEntity.jgJgxwOtherActionEntity;
        List<JgJgxwOtherActionEntity> list=jpaQueryFactory.selectFrom(q).
                where(q.delFlag.eq(Constant.NO_DELETE)).fetch();
        HashMap map=new HashMap();
        for (JgJgxwOtherActionEntity jgJgxwOther:list) {
            String address=jgJgxwOther.getImplementInstitutio();
            Long count=jpaQueryFactory.select(q.implementInstitutio.count()).from(q).where(
                    q.delFlag.eq(Constant.NO_DELETE),q.actionId.eq(jgJgxwOther.getActionId()),q.implementInstitutio.eq(address)).fetchOne();
            Long value=(Long)map.get(address);
            if(value==null) {
                if(count!=0) {
                    map.put(address, count);
                }
            }else {
                value=count.longValue()+value.longValue();
                map.put(address,value);
            }
        }
        return map;
    }

    @Override
    public HashMap getCountByYear(String year) {
        QJgJgxwOtherActionEntity q=QJgJgxwOtherActionEntity.jgJgxwOtherActionEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        List<JgJgxwOtherActionEntity> list=jpaQueryFactory.selectFrom(q).
                where(q.delFlag.eq(Constant.NO_DELETE)).fetch();
        HashMap map=new HashMap();
        for (JgJgxwOtherActionEntity jgJgxwOther:list) {
            String address=jgJgxwOther.getImplementInstitutio();
            ComparableExpressionBase<?> creatYear = q.createTime.year();
            predicate =ExpressionUtils.and(predicate,((NumberExpression) creatYear).stringValue().eq(year)) ;
            Long count=jpaQueryFactory.select(q.implementInstitutio.count()).from(q).where(
                    q.delFlag.eq(Constant.NO_DELETE),q.actionId.eq(jgJgxwOther.getActionId()),q.implementInstitutio.eq(address),predicate).fetchOne();
            Long value=(Long)map.get(address);
            if(value==null) {
                if(count!=0) {
                    map.put(address, count);
                }
            }else {
                value=count.longValue()+value.longValue();
                map.put(address,value);
            }
        }
        return map;
    }

    @Override
    public Long getOpCheck(HttpServletRequest request) {

        QJgJgxwOtherActionEntity q=QJgJgxwOtherActionEntity.jgJgxwOtherActionEntity;
        /**
         * 获取suser
         */
        R r = serviceUtil.getUserInfoByRequest(request);
        String suserName = "";
        String location = "";
        String address="";
        String userUnit ="";
        String orgName="";
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            /**
             * 获取用户的省份
             */
            orgName = userInfo.getOrgName();

        }
        Long count=jpaQueryFactory.select(q.implementInstitutio.count()).from(q).where(q.implementInstitutio.eq(orgName),q.delFlag.eq(Constant.NO_DELETE)).fetchOne();
        return count;
    }

    @Override
    public List<JgJgxwOtherActionEntity> getList(String superviseItemCode, String recordUniqueIdentity, String actionName, String actionCode, String checkBehaviorNumber, String superviseObject) {

        QJgJgxwOtherActionEntity qOther = QJgJgxwOtherActionEntity.jgJgxwOtherActionEntity;
        Predicate predicate = qOther.isNotNull().or(qOther.isNull());
        predicate = ("".equals(superviseItemCode) || superviseItemCode == null) ? predicate : ExpressionUtils.and(predicate, qOther.superviseItemCode.like("%"+superviseItemCode+"%"));
        predicate = ("".equals(recordUniqueIdentity) || recordUniqueIdentity == null) ? predicate : ExpressionUtils.and(predicate, qOther.recordUniqueIdentity.like("%"+recordUniqueIdentity+"%"));
        predicate = ("".equals(actionName) || actionName == null) ? predicate : ExpressionUtils.and(predicate, qOther.actionName.like("%"+actionName+"%"));
        predicate = ("".equals(actionCode) || actionCode == null) ? predicate : ExpressionUtils.and(predicate, qOther.actionCode.like("%"+actionCode+"%"));
        predicate = ("".equals(checkBehaviorNumber) || checkBehaviorNumber == null) ? predicate : ExpressionUtils.and(predicate, qOther.checkBehaviorNumber.like("%"+checkBehaviorNumber+"%"));
        predicate = ("".equals(superviseObject) || superviseObject == null) ? predicate : ExpressionUtils.and(predicate, qOther.superviseObject.like("%"+superviseObject+"%"));
        predicate = ExpressionUtils.and(predicate, qOther.delFlag.eq(Constant.NO_DELETE)) ;

        return  jpaQueryFactory
                .selectFrom(qOther)
                .where(
                        predicate
                )
                .orderBy(qOther.createTime.desc())
                .fetch();
    }

    @Override
    public List<JgJgxwOtherActionEntity> queryByIds(List<String> idList) {
        return otherDao.findAllById(idList);
    }

    @Override
    public Integer getTotalCount() {
        QJgJgxwOtherActionEntity q = QJgJgxwOtherActionEntity.jgJgxwOtherActionEntity;
        return (int)jpaQueryFactory.selectFrom(q).where(q.delFlag.eq(Constant.NO_DELETE)).fetchCount();
    }

    @Override
    public List<JgJgxwOtherActionEntity> getApList() {

        QJgJgxwOtherActionEntity q = QJgJgxwOtherActionEntity.jgJgxwOtherActionEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());
        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE));
        return jpaQueryFactory.selectFrom(q).where(predicate).fetch();
    }


}
